#
# Copyright (c) 2024 Black Sesame Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os

IDL_TUPLE_PATTERN = "${PKG_PARENT_DIR}/${PKG_NAME}:msg/"
TARGET_DEP_PATTERN = "${PKG_PARENT_DIR}/${PKG_NAME}/msg/"

def replace_path(s, pkg_name, pkg_parent_dir):
    current_path = os.path.dirname(os.path.abspath(__file__))
    return s.replace('${CURRENT_DIR}', current_path).replace('${PKG_PARENT_DIR}', pkg_parent_dir).replace('${PKG_NAME}', pkg_name)

def update_path(src_dict, pkg_name, pkg_parent_dir, idl_filenames):
    for k, v in src_dict.items():
        if isinstance(v, str):
            src_dict[k] = replace_path(v, pkg_name, pkg_parent_dir)
        elif isinstance(v, list):
            if isinstance(k, str) and "idl_tuples" == k:
                for idl_filename in idl_filenames:
                    src_dict[k].append(IDL_TUPLE_PATTERN + idl_filename)

            if isinstance(k, str) and "target_dependencies" == k:
                for idl_filename in idl_filenames:
                    src_dict[k].append(TARGET_DEP_PATTERN + idl_filename)

            src_dict[k] = [replace_path(item, pkg_name, pkg_parent_dir) if isinstance(item, str) else item for item in v]

def check_directory(path):
    abs_path = os.path.abspath(path)
    pkg_name = os.path.basename(abs_path)
    pkg_parent_dir = os.path.dirname(abs_path)
    msg_directory = os.path.join(path, 'msg')
    idl_list = []

    if os.path.exists(msg_directory) and any(file.endswith('.idl') for file in os.listdir(msg_directory)):
        for filename in os.listdir(msg_directory):
            if filename.endswith('.idl'):
                idl_list.append(filename)
        return True, pkg_name, pkg_parent_dir, idl_list
    else:
        return False, None, None, None